package cn.tedu.weibo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        //配置白名单
        String[] urls = {"/","/index.html","/reg.html","/login.html",
                "/v1/users/reg","/v1/users/login","/v1/users/logout"};
        http.authorizeHttpRequests()     //请求认证管理
                .mvcMatchers(urls).permitAll() //匹配上面的所有路径 直接放行
                .anyRequest().authenticated(); //其它所有路径  必须通过登录认证后才能放行
        //调用框架提供的登录页面
//        http.formLogin();
        //配置没有登录的时候跳转到自己的登录页面
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                //没有登录 并请求了需要登录的资源时执行此处代码
                response.sendRedirect("/login.html");
            }
        });
        //禁用跨域攻击的防御
        http.csrf().disable();
    }
    //配置认证管理器
    @Bean  //添加此注解 是为了能够通过Spring框架自动装配
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        //设置不加密
        return NoOpPasswordEncoder.getInstance();
    }



}

